package org.hepeng.workx.mybatis.builder.annotation;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.session.Configuration;
import org.hepeng.workx.extension.XLoader;
import org.hepeng.workx.mybatis.MybatisConstant;
import org.hepeng.workx.mybatis.mapper.MappedStatementSupplier;
import org.hepeng.workx.mybatis.mapper.TableMapMetadata;
import org.hepeng.workx.util.ObjectProcessor;

import java.util.Objects;

/**
 * @author he peng
 */
public class MapperAnnotationBuilderParseObjectProcessor implements ObjectProcessor<MapperAnnotationBuilderParseObjectProcessor.ParseProcessObject, MapperAnnotationBuilderParseObjectProcessor.ParseProcessObject> {

    protected static final MappedStatementSupplier MAPPED_STATEMENT_SUPPLIER = XLoader.getXLoader(MappedStatementSupplier.class , MybatisConstant.MYBATIS_X_POINT_DIRECTORY).getX();

    @Override
    public ParseProcessObject preProcess(ParseProcessObject preProcessObject) {
        return preProcessObject;
    }

    @Override
    public ParseProcessObject postProcess(ParseProcessObject postProcessObject) {
        TableMapMetadata tableMapMetaData = TableMapMetadata.parse(postProcessObject.getType());
        if (Objects.nonNull(tableMapMetaData)) {
            MAPPED_STATEMENT_SUPPLIER.initialize(tableMapMetaData , postProcessObject.getAssistant() , postProcessObject.getConfiguration());
            MAPPED_STATEMENT_SUPPLIER.triggerAllSupplier();
        }
        return postProcessObject;
    }

    @Builder
    @Setter
    @Getter
    public static class ParseProcessObject {
        private final Configuration configuration;
        private final MapperBuilderAssistant assistant;
        private final Class<?> type;
    }
}
